#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <sys/types.h>


int main(int argc, char const *argv[])
{
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("socket");
        return 1;
    }

    // 连接服务器 120.26.28.32 80
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(80);
    server_addr.sin_addr.s_addr = inet_addr("120.26.28.32");

    int ret = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret == -1)
    {
        perror("connect");
        return 1;
    }
    else
    {
        printf("connect success\n");
    }

    // 设置http请求协议
    char *http_request = "GET /doc/a.txt HTTP/1.1\r\nHost:120.26.28.32\r\n\r\n";
    write(sockfd, http_request, strlen(http_request));

    // 读取服务器返回的数据
    char buf[1024] = {0};
    read(sockfd, buf, sizeof(buf));
    printf("%s\n", buf);

    // 找到文本大小
    char *p = strstr(buf, "Content-Length:");
    int len = atoi(p + strlen("Content-Length:"));
    
    char tmp[1024] = {0};
    strncpy(tmp, buf, len);

    char *q = strstr(tmp, " ");
    char data[1024] = {0};
    strncpy(data, q + 1, 2);
    printf("文件大小：%s\n", data);

    


    // 关闭套接字
    close(sockfd);

    return 0;
}
